<script setup lang="ts">
  import { computed, onMounted, ref, watchEffect } from 'vue';
  import {
    ElButton,
    ElCheckbox,
    ElCol,
    ElForm,
    ElFormItem,
    ElInput,
    ElInputNumber,
    ElOption,
    ElRow,
    ElSelect,
    ElSlider,
    ElText,
  } from 'element-plus';
  import ReceiveMessage from '/@/core/communication/ReceiveMessage';
  import { ReceiveMessageType, SendMessageType } from '/@/config/DeclareGlobal';
  import { changeModel, ChangeModelData } from '/@/core/communication/interface/ISendUnity';
  import { getAllDevices } from '/@/views/DigitalTwin/newleft/service/defaultId';
  import store from '/@/views/DigitalTwin/newleft/manage/store';
  import { saveEntityAttributes } from '/@/api/thingsborad/entity/entity';
  //是否正在修改数据，如果正在修改，则不要接收数据
  let isModifying = false;
  // 定义表单数据
  const form = ref({
    type: '网格',
    group: 'default',
    orientations: 'default',
    level: 'default',
    backgroundColor: 'rgba(30, 36, 48, 1)',
    longitude: 116.405285,
    latitude: 39.904989,
    altitude: 0,
    start: true,
    pickup: true,
    shadow: true,
    shadow1: true,
    opacity: 1,
    // 表格数据：每行一个 (X, Y, Z)
    data: {
      name: '立方体',
      position: { x: 0, y: 0, z: 0 },
      scale: { x: 0, y: 0, z: 1 },
      rotation: { x: 0, y: 0, z: 0 },
    },
    id: null, // 临时存储匹配到的设备ID
  });
  // ReceiveMessage.addListener(MessageType.SelectedInfo, (e) => {
  //   console.log('Received e.data:', JSON.stringify(e.data, null, 2));
  // });
  onMounted(async () => {
    // 定义消息监听器
    const listener = (e: any) => {
      try {
        const data = JSON.parse(JSON.stringify(e));
        handleSelectedInfo(data);
      } catch (error) {
        console.error('消息处理错误:', error);
      }
    };

    // 添加监听器
    ReceiveMessage.addListener(ReceiveMessageType.SelectedInfo, listener);
    // 获取所有设备
    try {
      // 加载设备列表并赋值给响应式变量
      const devices = await getAllDevices();
      deviceList.value = devices; // 正确赋值到 .value
    } catch (error) {
      console.error('加载设备列表失败:', error);
    }
  });
  const deviceList = ref([]);
  // let deviceProfileIdValue = '';
  const handleSelectedInfo = (e: any) => {
    const safeData = e.data || {};
    if (isModifying) return;
    // console.log('Received e.data:', JSON.stringify(e.data, null, 2));
    form.value.data = {
      name: safeData.name ?? form.value.data.name,
      position: {
        x: safeData.position?.x ?? form.value.data.position.x,
        y: safeData.position?.y ?? form.value.data.position.y,
        z: safeData.position?.z ?? form.value.data.position.z,
      },
      scale: {
        x: safeData.scale?.x ?? form.value.data.scale.x,
        y: safeData.scale?.y ?? form.value.data.scale.y,
        z: safeData.scale?.z ?? form.value.data.scale.z,
      },
      rotation: {
        x: safeData.rotation?.x ?? form.value.data.rotation.x,
        y: safeData.rotation?.y ?? form.value.data.rotation.y,
        z: safeData.rotation?.z ?? form.value.data.rotation.z,
      },
    };
    // console.log('验证数据:', form.value.data);
  };
  const changeValue = () => {
    const data: ChangeModelData = {
      type: SendMessageType.ChangeModel,
      data: {
        name: form.value.data.name,
        position: {
          x: Number(form.value.data.position.x),
          y: Number(form.value.data.position.y),
          z: Number(form.value.data.position.z),
        },
        rotation: {
          x: Number(form.value.data.rotation.x),
          y: Number(form.value.data.rotation.y),
          z: Number(form.value.data.rotation.z),
        },
        scale: {
          x: Number(form.value.data.scale.x),
          y: Number(form.value.data.scale.y),
          z: Number(form.value.data.scale.z),
        },
      },
    };
    changeModel(data);
    isModifying = false;
    saveAllAttributes();
  };
  const focusInput = () => {
    isModifying = true;
  };
  // 监听表单 name 变化，自动查找对应设备 ID 并提交
  watchEffect(() => {
    const name = form.value.data.name;
    if (name) {
      // 查找匹配的设备
      const matchedDevice = deviceList.value.find((device) => device.name === name);
      const deviceId = matchedDevice?.id?.id || null; // 提取实际的 id 值

      // 更新表单的 id 字段
      form.value.id = deviceId;

      // 提交到新的 Vuex 状态 selectedDeviceId
      if (deviceId) {
        store.commit('SET_SELECTED_DEVICE_ID', deviceId);
      } else {
        store.commit('SET_SELECTED_DEVICE_ID', null); // 清空选中ID
      }
    } else {
      // 清空表单和 Vuex 的设备 ID
      form.value.id = null;
      store.commit('SET_SELECTED_DEVICE_ID', null);
    }
  });

  // 属性更改上传到后端
  const saveAllAttributes = async () => {
    // 通过计算属性获取选中的设备 ID
    const selectedDeviceId = computed(() => store.getters.selectedDeviceId);

    try {
      const attributesToSave = [
        { key: 'LocalScale', value: form.value.data.scale },
        { key: 'Position', value: form.value.data.position },
        { key: 'Rotation', value: form.value.data.rotation },
      ];

      const promises = attributesToSave.map((attr) => {
        return saveEntityAttributes({
          entityType: 'DEVICE',
          entityId: selectedDeviceId.value,
          scope: 'SHARED_SCOPE', // 共享属性作用域
          key: attr.key,
          value: attr.value, // 确保 value 是后端接受的格式
        });
      });

      const responses = await Promise.all(promises);
      console.log('所有属性保存成功:', responses);
    } catch (error) {
      console.error('保存属性失败:', error);
    }
  };
</script>

<template>
  <div class="basicComponent">
    <el-form :model="form" label-width="6.5vw">
      <el-form-item label="模型管理" class="right-menu-title" />
      <el-button id="editModel">编辑模型</el-button>
      <!-- 基础设置 -->
      <el-form-item label="基础" class="right-menu-title" />
      <el-form-item label="类型" style="color: #fff">
        <el-input v-model="form.type" />
      </el-form-item>
      <el-form-item label="名称" style="color: #fff">
        <el-input v-model="form.data.name" />
      </el-form-item>
      <el-form-item label="所属分组">
        <el-select v-model="form.group" placeholder="请选择">
          <el-option label="默认" value="default" />
          <el-option label="自定义" value="custom" />
        </el-select>
      </el-form-item>
      <el-form-item label="启用">
        <el-checkbox v-model="form.start" />
      </el-form-item>
      <el-form-item label="可拾取">
        <el-checkbox v-model="form.pickup" />
      </el-form-item>
      <el-form-item label="接受阴影">
        <el-checkbox v-model="form.shadow" />
      </el-form-item>
      <el-form-item label="生成阴影">
        <el-checkbox v-model="form.shadow1" />
      </el-form-item>
      <el-form-item label="透明度">
        <el-slider
          v-model="form.opacity"
          :min="0"
          :max="1"
          step="0.01"
          show-input
          label="Opacity"
          class="form-slider clean-border"
          controls-position="right"
        />
      </el-form-item>
    </el-form>
    <el-form-item label="固定朝向">
      <el-select v-model="form.orientations" placeholder="请选择">
        <el-option label="默认" value="default" />
        <el-option label="自定义" value="custom" />
      </el-select>
    </el-form-item>
    <el-form-item label="渲染层级">
      <el-select v-model="form.level" placeholder="请选择">
        <el-option label="默认" value="default" />
        <el-option label="自定义" value="custom" />
      </el-select>
    </el-form-item>
    <el-form-item label="经度">
      <el-input-number
        v-model="form.longitude"
        controls-position="right"
        class="form-slider form-number"
      />
    </el-form-item>
    <el-form-item label="纬度">
      <el-input-number
        v-model="form.latitude"
        controls-position="right"
        class="form-slider form-number"
      />
    </el-form-item>
    <el-form-item label="海拔">
      <el-input-number
        v-model="form.altitude"
        controls-position="right"
        class="form-slider form-number"
      />
    </el-form-item>
    <!--    表格-->
    <el-row id="tableXyz">
      <el-col style="margin-top: 3vh">
        <el-text
          style="
            color: red;
            width: 4vw !important;
            margin-left: 5vw !important;
            font-size: 0.8vw;
            display: inline-block;
          "
          >x
        </el-text>
        <el-text
          style="color: green; width: 4vw !important; font-size: 0.8vw; display: inline-block"
          >y
        </el-text>
        <el-text
          style="color: #3636ef; width: 4vw !important; font-size: 0.8vw; display: inline-block"
          >z
        </el-text>
      </el-col>
      <el-col>
        <el-text style="width: 3vw !important; margin-left: 0.8vw !important; display: inline-block"
          >位置
        </el-text>
        <el-input
          v-model="form.data.position.x"
          placeholder="X轴位置"
          @focus="focusInput"
          @change="changeValue"
        />
        <el-input
          v-model="form.data.position.y"
          placeholder="Y轴位置"
          @focus="focusInput"
          @change="changeValue"
        />
        <el-input
          v-model="form.data.position.z"
          placeholder="Z轴位置"
          @focus="focusInput"
          @change="changeValue"
        />
      </el-col>
      <el-col>
        <el-text style="width: 3vw !important; margin-left: 0.8vw !important; display: inline-block"
          >缩放
        </el-text>
        <el-input
          v-model="form.data.scale.x"
          placeholder="X轴缩放"
          @focus="focusInput"
          @change="changeValue"
        />
        <el-input
          v-model="form.data.scale.y"
          placeholder="Y轴缩放"
          @focus="focusInput"
          @change="changeValue"
        />
        <el-input
          v-model="form.data.scale.z"
          placeholder="Z轴缩放"
          @focus="focusInput"
          @change="changeValue"
        />
      </el-col>
      <el-col>
        <el-text style="width: 3vw !important; margin-left: 0.8vw !important; display: inline-block"
          >旋转
        </el-text>
        <el-input
          v-model="form.data.rotation.x"
          placeholder="X轴旋转"
          @focus="focusInput"
          @change="changeValue"
        />
        <el-input
          v-model="form.data.rotation.y"
          placeholder="Y轴旋转"
          @focus="focusInput"
          @change="changeValue"
        />
        <el-input
          v-model="form.data.rotation.z"
          placeholder="Z轴旋转"
          @focus="focusInput"
          @change="changeValue"
        />
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
  .basicComponent {
    background-color: #1e2430;
    height: 95vh;
    overflow: auto;
    color: #c9cbd5 !important;
    font-size: 0.8vw;
  }

  :deep(.el-form-item) {
    margin-left: 0.8vw;
    padding-top: 1.2vh;
  }

  #editModel {
    margin-left: 1vw !important;
    background: rgb(69 131 255);
  }

  #editModel :hover {
    background: rgb(75, 111, 198);
    color: white;
  }

  .el-form-item >>> .el-form-item__label {
    justify-content: flex-start;
    width: 6vw;
    color: #c9cbd5;
  }

  .el-form-item >>> .el-form-item__content {
    background-color: #1e2430;
    width: 3vw;
    height: 2vh;
  }

  .el-form-item >>> input {
    color: #c9cbd5 !important;
  }

  .right-menu-title :deep(.el-form-item__label) {
    font-size: 1vw;
    font-weight: 550;
    --color: #fff;
  }

  :deep(.el-input__wrapper) {
    box-shadow: none;
  }

  :deep(.el-input__wrapper) :hover {
    box-shadow: 0 0 0 1px white;
    border-radius: 2px;
  }

  :deep(.el-input__wrapper) :focus {
    box-shadow: 0 0 0 1px #4583ff;
    border-radius: 2px;
  }

  :deep(.el-input__wrapper .el-input__inner) {
    width: 10vw !important;
    height: 5vh !important;
    margin-left: -0.8vw;
    font-size: 0.8vw;
    text-align: left;
    padding-left: 1vw;
  }

  /* 选择按钮 */
  :deep(.el-checkbox) {
    margin-left: 1vw;
  }

  /* 选择框 */
  :deep(.el-select__wrapper) {
    width: 10vw !important;
    box-shadow: none; /* 取消阴影 */
  }

  :deep(.el-slider__button) {
    width: 1vw;
    height: 1vw;
  }

  :deep(.el-slider__runway) {
    margin-right: 1vw;
    margin-left: 1vw;
  }

  :deep(.el-input-number__increase) {
    margin-right: 1vw;
    display: none;
  }

  :deep(.el-input-number__decrease) {
    margin-right: 1vw;
    display: none;
  }

  /* 鼠标悬停时显示增加减少按钮 */
  .form-slider:hover :deep(.el-input-number__increase) {
    display: flex;
    border: none;
  }

  .form-slider:hover :deep(.el-input-number__decrease) {
    display: flex;
    border: none;
    margin-left: -0.5vw;
  }

  .form-slider :deep(.el-input) {
    margin-left: 0.6vw;
  }

  /* 数字框 */
  .form-number :deep(.el-input-number) {
    width: 22vw !important;
    margin-left: 1vw;
  }

  .form-number :deep(.el-input-number__increase) {
    border: none;
  }

  .form-number :deep(.el-input-number__decrease) {
    border: none;
  }

  /* 清除边框样式 */
  .clean-border :deep(.el-input__wrapper) :hover {
    box-shadow: none;
  }

  .clean-border :deep(.el-input__wrapper) :focus {
    box-shadow: none;
  }

  /* 表 */
  #tableXyz > .el-col > .el-input {
    width: 4vw;
  }

  #tableXyz :deep(.el-input__inner) {
    width: 2vw !important;
  }

  /* 整个滚动条 */
  ::-webkit-scrollbar {
    width: 0.3vw; /* 宽度 */
    background-color: rgb(123, 255, 0); /* 背景色 */
  }

  /* 滚动条轨道 */
  ::-webkit-scrollbar-track {
    background: #282c34; /* 轨道颜色 */
    border-radius: 0; /* 轨道圆角 */
  }

  /* 滚动条的滑块 */
  ::-webkit-scrollbar-thumb {
    background-color: #2926c3; /* 滑块颜色 */
    border-radius: 2px; /* 滑块圆角 */
    border: 0.8vw solid #535f79; /* 滑块边框 */
  }

  /* 滑块在悬停或者点击时的样式 */
  ::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8; /* 悬停时滑块颜色 */
  }
</style>
